<template>
	<div class="dialog-box">
		<div class="chattingRecord">
			<div class="not-chat">已展示全部消息~</div>
			<template v-for="(chatItem, index) in props.chattingRecordList" :key="'chat-item' + index">
				<div v-if="chatItem.identity === EIdentity.StartCommunication" class="communication-time-box">
					<div class="communication-time">{{ chatItem.time }} 开始沟通</div>
				</div>
				<div v-else class="chat-item" :class="{ customer: chatItem.identity === props.identity }">
					<!-- <div class="title">我 今天 15:51:33</div> -->
					<div class="title">{{ chatItem.name }} {{ formatPastComputed(chatItem.time) }}</div>
					<div class="content" v-if="[EMsgType.text, EMsgType.img].includes(chatItem.ContentType)">
						<span v-if="chatItem.ContentType === EMsgType.text">{{ chatItem.content }}</span>
						<el-image
							v-else-if="chatItem.ContentType === EMsgType.img"
							style="width: 100px; height: 100px"
							:src="chatItem.content"
							:initial-index="1"
							fit="fill"
							:preview-src-list="[chatItem.content!]"
							lazy
						/>
					</div>
					<div
						v-else-if="chatItem.ContentType === EMsgType.file"
						class="file"
						@dblclick="handleFileDown(chatItem.content.title, chatItem.content.link)"
					>
						<el-image style="width: 40px; height: 40px" :src="chatItem.content.icon || defaultImgIcon" fit="fill" lazy />
						<div class="info">
							<div class="title">{{ chatItem.content.title }}</div>
							<span class="size">{{ chatItem.content.size }}</span>
							<span class="status">{{ chatItem.content.status }}</span>
						</div>
					</div>
				</div>
			</template>
		</div>
	</div>
	<div class="handler">
		<div class="input" ref="inputRef" @input="getContent" contenteditable="true">{{ content }}</div>
		<div class="tool-bar">
			<div class="tool">
				<img src="../../../../assets/icon/image.svg" alt="" @click="handlerImgUpload" />
				<div class="biaoq" v-click-outside="onClickOutside">
					<img src="../../../../assets/icon/biaoq.svg" alt="" @click="handlerShowEmoji" />
					<div class="emoji-content" :style="[isShowEmoji ? 'display: block;' : '']">
						<div v-for="emojiKey in Object.keys(emojiObj)" :key="emojiKey" class="emoji" @click="handlerClickEmoji(emojiKey as keyof emojiKeyType)">
							{{ emojiObj[emojiKey] }}
						</div>
					</div>
				</div>
				<img src="../../../../assets/icon/file.svg" alt="" @click="handlerFileUpload" />
			</div>
			<div class="submit">
				<el-button
					type="primary"
					size="default"
					@click="
						() => {
							state.msgTypes = EMsgType.text;
							emitSendMessageReq();
						}
					"
					>发送</el-button
				>
			</div>
		</div>
	</div>
	<Upload
		style="display: none"
		accept=".jpg,.png"
		input-type="7"
		ref="uploadRef"
		@on-change-file-list="(file) => handlerChangeFileList(file, 'uploadRef')"
	>
		<button ref="uploadBtnRef">上传</button>
	</Upload>
	<Upload style="display: none" input-type="7" ref="uploadFileRef" @on-change-file-list="(file) => handlerChangeFileList(file, 'uploadFileRef')">
		<button ref="uploadFileBtnRef">上传</button>
	</Upload>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { ClickOutside as vClickOutside, ElMessage } from 'element-plus';
import { EMsgType, EIdentity, IChattingRecord } from '../type';
import { sizeTostr, handleFileDown } from '/@/utils/extendMethods';
import { formatDate, formatPast } from '/@/utils/formatTime';
import { useVModel } from '@vueuse/core';
import Upload from '/@/components/Linxyun/FileClient/index.vue';
import defaultImgIcon from '/@/assets/icon/file-icon-default.png';

interface IState {
	serveType: number | null;
	Recver: string;
	chatUserID: string; // 用户ID
	msgTypes: EMsgType;
	uploadUrl: string;
	fileUrlPrefix: string;
	self: Record<string, any>;
	isRetract: boolean;
	fileIcon: string;
	fileInfo: Record<string, any>;
	isShowEmoji: boolean;
}

const props = withDefaults(defineProps<{ chattingRecordList: IChattingRecord[]; identity: EIdentity; content: any }>(), {});
const emits = defineEmits(['sendMessageReq', 'fileSendMessage', 'saveChattingRecord']);
const emojiObj = reactive({
	grinning: '😀',
	grin: '😁',
	joy: '😂',
	smiley: '😃',
	smile: '😄',
	sweat_smile: '😅',
	laughing: '😆',
	satisfied: '😆',
	innocent: '😇',
	smiling_imp: '😈',
	wink: '😉',
	blush: '😊',
	yum: '😋',
	relieved: '😌',
	heart_eyes: '😍',
	sunglasses: '😎',
	smirk: '😏',
	neutral_face: '😐',
	expressionless: '😑',
	unamused: '😒',
	sweat: '😓',
	pensive: '😔',
	confused: '😕',
	confounded: '😖',
	kissing: '😗',
	kissing_heart: '😘',
	kissing_smiling_eyes: '😙',
	kissing_closed_eyes: '😚',
	stuck_out_tongue: '😛',
	stuck_out_tongue_winking_eye: '😜',
	stuck_out_tongue_closed_eyes: '😝',
	disappointed: '😞',
	worried: '😟',
	angry: '😠',
	rage: '😡',
	cry: '😢',
	persevere: '😣',
	triumph: '😤',
	disappointed_relieved: '😥',
	frowning: '😦',
	anguished: '😧',
	fearful: '😨',
	weary: '😩',
	sleepy: '😪',
	tired_face: '😫',
	grimacing: '😬',
	sob: '😭',
	open_mouth: '😮',
	hushed: '😯',
	cold_sweat: '😰',
	scream: '😱',
	astonished: '😲',
	flushed: '😳',
	sleeping: '😴',
	dizzy_face: '😵',
	no_mouth: '😶',
	mask: '😷',
	smile_cat: '😸',
	joy_cat: '😹',
	smiley_cat: '😺',
	heart_eyes_cat: '😻',
	smirk_cat: '😼',
	kissing_cat: '😽',
	pouting_cat: '😾',
	crying_cat_face: '😿',
	scream_cat: '🙀',
	slightly_frowning_face: '🙁',
	slightly_smiling_face: '🙂',
	upside_down_face: '🙃',
	face_with_rolling_eyes: '🙄',
	'woman-gesturing-no': '🙅‍♀️',
	no_good: '🙅‍♀️',
	'man-gesturing-no': '🙅‍♂️',
	'woman-gesturing-ok': '🙆‍♀️',
	ok_woman: '🙆‍♀️',
	'man-gesturing-ok': '🙆‍♂️',
	'woman-bowing': '🙇‍♀️',
	'man-bowing': '🙇‍♂️',
	bow: '🙇‍♂️',
	see_no_evil: '🙈',
	hear_no_evil: '🙉',
	speak_no_evil: '🙊',
	'woman-raising-hand': '🙋‍♀️',
	raising_hand: '🙋‍♀️',
	'man-raising-hand': '🙋‍♂️',
	raised_hands: '🙌',
	'woman-frowning': '🙍‍♀️',
	person_frowning: '🙍‍♀️',
	'man-frowning': '🙍‍♂️',
	'woman-pouting': '🙎‍♀️',
	person_with_pouting_face: '🙎‍♀️',
	'man-pouting': '🙎‍♂️',
	pray: '🙏',
});
type emojiKeyType = typeof emojiObj;
const state = reactive<IState>({
	serveType: null,
	Recver: '',
	chatUserID: '',
	msgTypes: EMsgType.text,
	uploadUrl: '',
	fileUrlPrefix: '',
	self: {},
	isRetract: true,
	fileIcon: defaultImgIcon,
	fileInfo: {},
	isShowEmoji: false,
});
const { isShowEmoji } = toRefs(state);

if (localStorage.getItem('setting')) {
	state.fileUrlPrefix = JSON.parse(localStorage.getItem('setting')!).ImagUrl;
}
const formatPastComputed = computed(() => {
	return (date: Date) => {
		return formatPast(new Date(date));
	};
});

const onClickOutside = () => {
	isShowEmoji.value = false;
};
const content = useVModel(props, 'content', emits);
const handlerClickEmoji = (emojiKey: keyof emojiKeyType) => {
	content.value += emojiObj[emojiKey];
};

const inputRef = ref();
const getContent = () => {
	content.value = inputRef.value.innerHTML || '';
	// console.log('state.content', state.content);
};

const uploadRef = ref<InstanceType<typeof Upload>>();
const uploadBtnRef = ref();
// 上传图片
const handlerImgUpload = () => {
	uploadBtnRef.value?.click();
	state.msgTypes = EMsgType.img;
};
// 上传文件
const uploadFileRef = ref<InstanceType<typeof Upload>>();
const uploadFileBtnRef = ref();
const handlerFileUpload = () => {
	uploadFileBtnRef.value?.click();
	state.msgTypes = EMsgType.file;
};

const handlerShowEmoji = () => {
	isShowEmoji.value = !isShowEmoji.value;
	console.log('handlerShowEmoji', isShowEmoji.value);
};

const emitSendMessageReq = () => {
	emits('sendMessageReq');
};
const handlerChangeFileList = async (file: Record<string, any>, _uploadRef: 'uploadRef' | 'uploadFileRef') => {
	if (file.size > 1024 * 1024 * 10) {
		return ElMessage.error('只允许上传10M以内的图片或者文件');
	}
	const resImg: { name: string; url: string }[] | undefined =
		_uploadRef === 'uploadRef' ? await uploadRef.value?.uploadSubmit() : await uploadFileRef.value?.uploadSubmit();
	console.log('handlerChangeFileList', resImg);
	if (resImg && resImg?.length === 1) {
		state.uploadUrl = state.fileUrlPrefix + resImg[0].url;
		state.fileInfo = file;
		// sendMessageReq();
		emits('fileSendMessage', {
			msgTypes: state.msgTypes,
			uploadUrl: state.uploadUrl,
			fileInfo: state.fileInfo,
		});
	} else {
		ElMessage.error('上传异常');
		// 本地保存聊天记录
		if (state.msgTypes === EMsgType.file) {
			const chattingRecord: IChattingRecord = {
				name: '我',
				time: formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS'),
				content: {
					link: state.uploadUrl,
					title: file.name,
					size: sizeTostr(file.size),
					status: '上传失败',
				},
				identity: EIdentity.Customer,
				ContentType: EMsgType.file,
			};
			emits('saveChattingRecord', chattingRecord);
			// saveChattingRecord(chattingRecord);
		}
	}
	_uploadRef === 'uploadRef' ? uploadRef.value?.fileListInnerClear() : uploadFileRef.value?.fileListInnerClear();
};
</script>
<style lang="scss" scoped>
.handler {
	border-top: 1px solid #e6e8eb;
	padding: 15px 15px 8px 15px;
	position: relative;
	.emoji-content {
		position: absolute;
		display: none;
		left: 10px;
		top: -190px;
		width: 360px;
		height: 180px;
		background-color: var(--next-color-white);
		overflow-y: auto;
		font-size: 20px;
		box-shadow: var(--el-box-shadow-light);

		.emoji {
			display: inline-flex;
			justify-content: center;
			width: 34px;
			height: 34px;
			cursor: pointer;
		}
	}
	.input {
		height: 50px;

		overflow-y: auto;
	}
	.tool-bar {
		display: flex;
		justify-content: space-between;
		.tool {
			display: flex;
			align-items: flex-end;
			img {
				width: 22px;
				cursor: pointer;
			}
			.biaoq {
				height: 22px;
				margin: 0 8px;
			}
		}
	}
}

.dialog-box {
	width: 100%;
	background-color: var(--next-color-white);
	padding: 20px 15px;
	overflow-y: auto;
	height: 404px;
}
.not-chat {
	text-align: center;
	color: #909399;
	font-size: 12px;
}
.communication-time-box {
	text-align: center;
}
.communication-time {
	display: inline-block;
	margin: 24px 12px 0;
	padding: 5px 12px;
	font-size: 12px;
	line-height: 18px;
	color: #606266;
	border-radius: 4px;
	background: #f5f7fa;
}
.chat-item {
	margin-bottom: 16px;
	.title {
		margin-bottom: 4px;
		font-size: 12px;
		line-height: 12px;
		color: #a4a0aa;
		min-width: 66px;
	}
	.content {
		font-size: 14px;
		word-break: break-all;
		border-radius: 4px;
		border-radius: 0 8px 8px 8px;
		background: #eff1f7;
		white-space: pre-line;
		line-height: 22px;
		padding: 12px;
		max-width: 80%;
		display: inline-block;
	}
	.file {
		display: flex;
		border: 1px solid #ebeef5;
		width: 298px;
		height: 65px;
		background: #fff;
		border-radius: 8px 0 8px 8px;
		padding: 12px 8px 12px 12px;
		cursor: pointer;
		.el-image {
			// margin: 12px 8px 12px 12px;
			margin-right: 10px;
		}
		.info {
			width: calc(100% - 55px);
			.title {
				color: #303133;
				text-align: left;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				width: 100%;
				margin-top: 3px;
				margin-bottom: 8px;
			}
			span {
				color: #909399;
				font-weight: 400;
				&.size {
					margin-right: 10px;
				}
			}
		}
	}
}
.customer {
	display: flex;
	flex-direction: column;
	align-items: flex-end;

	.content {
		border-radius: 8px 0px 8px 8px;
	}
}
.retract-right {
	cursor: pointer;
}
</style>
